<template>
  <op-dialog
    title="Scan QR code"
    v-model="dialogVisible"
    v-if="dialogVisible"
    :buttonList="[{ type: 'primary', prop: 'refresh', label: 'Refresh' }]"
    width="500px"
    @confirm="handleRefresh"
    noFullscreen
  >
    <div class="scan_qr_code">
      <h6>Draw with your mobile device</h6>
      <p>Scan this QR code to draw your signature with a mobile device</p>
      <span class="qr_code_box">
        <qrcode-vue
          class="qrcode"
          :value="`${qrCodeConfig.h5Url}?params=${jsonObj}`"
          :size="180"
        ></qrcode-vue>
      </span>
    </div>
    <!-- <div style="text-align: right">
      <el-button type="primary" @click="handleRefresh">Refresh</el-button>
    </div> -->
  </op-dialog>
</template>

<script setup>
import QrcodeVue from 'qrcode.vue';
import { apiMethods } from '@/utils/http.js';
import { ElMessage } from 'element-plus';
// import { getEnvDomain } from '@/utils/index.js';

const { qrCodeConfig } = defineProps({
  qrCodeConfig: {
    type: Object,
    default: () => ({}),
  },
});

// ref

const emits = defineEmits(['handleRefresh', 'getQRInfo']);

let dialogVisible = ref(false);
const jsonObj = ref({});

function init(row) {
  dialogVisible.value = true;
  getQRDetail();
}

// 獲取二維碼信息
function getQRDetail() {
  const { axiosMethod = 'post', requestUrl, params } = qrCodeConfig;
  if (!requestUrl) return;
  apiMethods[axiosMethod](requestUrl, params).then(res => {
    let data = res.data.data;
    let signatureCode = data?.signatureCode || '';

    if (!signatureCode) {
      ElMessage.error('Failed to obtain the QR code, please refresh and try again');
      return;
    }
    emits('getQRInfo', data);
    let obj = {
      ...params,
      ...qrCodeConfig.h5Params,
      signatureCode: signatureCode,
    };
    let str = JSON.stringify(obj);
    jsonObj.value = encodeURIComponent(str);
  });
}

// 重新刷新页面
function handleRefresh() {
  getQRDetail();
  emits('handleRefresh');
}

function buttonClick(prop) {
  switch (prop) {
    case 'close':
      dialogVisible.value = false;
      break;
  }
}

defineExpose({
  init,
  dialogVisible,
  buttonClick,
});
</script>

<style lang="scss" scoped>
.scan_qr_code {
  text-align: center;
  h6 {
    font-size: 14px;

    font-weight: 500;
    color: #303133;
    line-height: 20px;
    margin: 20px 0 10px;
  }
  p {
    font-size: 12px;
    font-weight: 400;
    color: #606266;
    line-height: 17px;
  }
  .qr_code_box {
    display: inline-block;
    margin-top: 10px;
    padding: 30px;
  }
}
</style>
